<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Java后端SSE</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>

<body>

Welcome<br/><input id="text" type="text" />
<button onclick="send()">发送消息</button>

<div id="message"></div>
</body>
<script type="text/javascript">
// var es = new EventSource("/thd/sseServlet");

// 可在跨域时使用该参数
var es = new EventSource("http://127.0.0.1:8899/thd/sseServlet", { withCredentials: true });




es.addEventListener("open", function (e) {
    console.log("open");
})
es.addEventListener("message", function (e) {
    console.log(e.data);
    document.getElementById('message').innerHTML += e.data + '<br/>';
})
es.addEventListener("error", function (e) {
    console.log("error")
    es.close();
})

es.addEventListener("customEvt", function (e) {
    console.log(e.data, e.lastEventId, e);
    document.getElementById('message').innerHTML += e.data + '<br/>';
})


<!--es.onopen = function (e) {-->
<!--    console.log("open")-->
<!--};-->
<!--es.onmessage = function (e) {-->
<!--    console.log(e.data);-->
<!--    document.getElementById('message').innerHTML += e.data + '<br/>';-->
<!--}-->

<!--es.oncustomEvt = function (e) {-->
<!--    console.log("custom:",e.data);-->
<!--    document.getElementById('message').innerHTML += e.data + '<br/>';-->
<!--}-->


es.onerror = function (e) {
    console.log("error")
    es.close()
}
</script>

</html>